/**
 * Token Service
 */

var GetToken = function(agentId, options){
	this.agentId = agentId;
	this.error = options.error;
	this.success = options.success;
	this.getToken();
};

GetToken.prototype._error = function(code, message){
	if(typeof this.error == 'function') {
		this.error(code, message);
	}
};

GetToken.prototype._success = function(data){
	if(typeof this.error == 'function') {
		this.success(data);
	}
};

GetToken.prototype.getToken = function(){
	var self = this;
	Mysql.query("SELECT agentId,token,expire,COUNT(*) AS c1 FROM AccessToken WHERE agentId="+Mysql.escape(self.agentId)+" LIMIT 1")
	.on('error', function(error){
		console.log('Mysql error: '+error);
		self._error(9999, 'Mysql error');
	})
	.on('result', function(result){
		if(result['c1'] == 0) {
			var newToken = components.string.genToken();
			Mysql.query("INSERT INTO AccessToken(agentId,token,expire) VALUES("+Mysql.escape(self.agentId)+","+Mysql.escape(newToken)+",NULL)")
			.on('error', function(error){
				console.log('Mysql error: '+error);
				self._error(9999, 'Mysql error');
			})
			.on('result', function(result){
				self._success({ id: result.insertId,token: newToken, agentId: self.agentId, expire: null });
			});
		}
		else {
			delete result.c1;
			self._success(result);
		}
	});
};

module.exports = GetToken;